package utl.mofen.script;

import java.sql.SQLException;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map.Entry;

import org.apache.log4j.Logger;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import utl.mofen.impl.DBOperator;
import utl.mofen.intf.IConfigLoader;
import utl.mofen.intf.IDBOperator;

public class ScriptObjectFactory {
	private static final Logger logger = Logger.getLogger(ScriptObjectFactory.class);
    static Hashtable<String, ScriptObjectCenter> socHash = new Hashtable<String, ScriptObjectCenter>();  
    
    public static IDBOperator getDBOperator(String dbid) throws SQLException
    {
		ComboPooledDataSource ds = new ComboPooledDataSource(dbid); 
        DBOperator ret = new DBOperator(ds.getConnection());
        logger.info("连接池" + dbid + "当前连接数" +ds.getNumConnections());
		return ret;
    }
    
    
    public static ScriptObjectCenter getSOC(String dbid)
	{
		ScriptObjectCenter ret = socHash.get(dbid);
		if (ret==null)
		{
			ret = new ScriptObjectCenter();	
			ret.setUseCache(false);   //使用缓存
			try {
				IConfigLoader sl = new ScriptLoader(dbid);
				ret.checkInitialize(sl);
				logger.info("脚本对象中心(" + dbid + ")初始化完成!");
			} catch (Exception e) {
				logger.error("脚本对象中心(" + dbid + ")初始化失败!");
				e.printStackTrace();
			}
			socHash.put(dbid, ret);
		}
		return ret;
	}
    
    public static void clearCache()
    {
    	Iterator<Entry<String, ScriptObjectCenter>> it = socHash.entrySet().iterator();
        while (it.hasNext())
        {
        	Entry<String, ScriptObjectCenter> entry = (Entry<String, ScriptObjectCenter>) it.next();
        	entry.getValue().loader.clearCache();

        } 
    }

}
